package com.contactbook.web.controller.group;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.contactbook.web.service.GroupClient;
import com.contactbook.web.util.GroupMessage;

import contactbook.model.Account;
import contactbook.model.Group;

public class AddGroupController extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;
	
	private static final String CONFIRM_ADD = "Ajouter";
	
	private GroupClient groupClient;
	
	public AddGroupController() {
		super();
    	groupClient = new GroupClient();
	}
	
    public void init() throws ServletException {
    	super.init();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Index");
		dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		Account account = (Account)session.getAttribute("account");
		String submit = request.getParameter("submit");
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Index");
	
		if (account != null) {	
			groupClient.login(account.getLogin(), account.getPassword());
		
			if (submit == null) {
				dispatcher = request.getRequestDispatcher("/addGroup.jsp");
			}
			else if (submit.equals(CONFIRM_ADD)) {
				GroupMessage message = addGroup(request);
				request.setAttribute("message", message);
				request.setAttribute("name", request.getParameter("name"));
				request.setAttribute("description", request.getParameter("description"));
				dispatcher = request.getRequestDispatcher("/addGroup.jsp");
			}
			else {
				dispatcher = request.getRequestDispatcher("/Group");
			}
			
			groupClient.logout();
		}
		
		dispatcher.forward(request, response);
	}
	
	private GroupMessage addGroup(HttpServletRequest request) {
		String name = request.getParameter("name");
		String description = request.getParameter("description");
		
		if (!name.equals("")) {
			Group group = groupClient.add(new Group(name, description));
			if (group != null)
				return GroupMessage.GROUP_CREATED_OK;
			else
				return GroupMessage.GROUP_CREATED_FAIL;
		}
		return GroupMessage.GROUP_CREATED_NAME_FAIL;
	}

	public void destroy() {
		super.destroy();
	}

}
